import createError from 'http-errors'
import { Response } from 'express'
/**
 * 请求成功
 * @param res
 * @param message
 * @param data
 * @param code
 */
function success<T>(res: Response, message: string, data?: T, code = 200) {
  res.json({
    code: code,
    message,
    data: data ?? {},
  })
}

/**
 * 请求失败
 * @param res
 * @param err
 */
function failure(res: Response, err: any) {
  // 默认响应
  let statusCode = 500
  let errors = '服务器错误。'

  // 如果是开发环境，显示详细错误信息
  if (process.env.NODE_ENV === 'development') {
    errors = err.message
  }

  if (err.name === 'ZodError') {
    statusCode = 400
    errors = err.issues.map((e: any) => e.message)
  } else if (err.name === 'JsonWebTokenError' || err.name === 'TokenExpiredError') {
    // Token 验证错误
    statusCode = 401
    errors = '您提交的 token 错误或已过期。'
  } else if (err instanceof createError.HttpError) {
    // http-errors 库创建的错误
    statusCode = err.status
    errors = err.message
  }

  res.json({
    code: statusCode,
    message: Array.isArray(errors) ? errors.join('; ') : errors,
    data: {},
  })
}

export { success, failure }
